import React, { PureComponent } from 'react';

// 如果 compiiler DOM 不存在，则加上
if ($('#compiler').length === 0) {
    $('body').append('<div id="compiler"></div>');
}

// 开发状态使用
export default class Compiler extends PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            status: undefined,
        };
        const xhr = new XMLHttpRequest();
        xhr.open('GET', `${WPT.loadScriptHost}/compile?url=${encodeURIComponent(this.props.url)}&t=${Date.now()}`);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                const { status } = JSON.parse(xhr.responseText);
                if (status === 'not found') {
                    this.setState({ status: 404 });
                } else if (status === 'done') {
                    window.location.reload();
                    this.setState({ status: 200 });
                }
            }
        };
        xhr.send();
    }

    render() {
        const { status } = this.state;
        let message = '编译中...';

        if (status === 404) {
            message = '路由不存在';
        }

        if (status === 200) {
            message = '编译完成';
        }

        return (
            <div
                style={{
                    height: '100vh',
                    width: '100%',
                    position: 'fixed',
                    top: 0,
                    left: 0,
                    zIndex: 9999,
                    background: '#ffffff',
                    padding: '.5rem',
                    boxSizing: 'border-box',
                    color: 'rgba(0,0,0,.65)',
                }}
            >
                <h2>{message}</h2>
            </div>
        );
    }
}
